// 任务管理模块

class TaskManager {
    constructor() {
        this.tasks = [];
        this.loadTasks();
    }
    
    // 获取所有任务
    getAllTasks() {
        return this.tasks;
    }
    
    // 添加任务
    addTask(title, description = '', priority = 'medium', dueDate = null, hours = 0) {
        const newTask = {
            id: Date.now(), // 使用时间戳作为唯一ID
            title: title,
            description: description,
            priority: priority, // low, medium, high
            status: 'pending', // pending, in-progress, completed
            dueDate: dueDate,
            hours: parseInt(hours) || 0,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        
        this.tasks.push(newTask);
        this.saveTasks();
        return newTask;
    }
    
    // 更新任务
    updateTask(id, updates) {
        const task = this.tasks.find(t => t.id === id);
        if (task) {
            // 确保工时是整数
            if (updates.hours !== undefined) {
                updates.hours = parseInt(updates.hours) || 0;
            }
            
            Object.assign(task, updates, { updatedAt: new Date().toISOString() });
            this.saveTasks();
            return task;
        }
        return null;
    }
    
    // 删除任务
    deleteTask(id) {
        const index = this.tasks.findIndex(t => t.id === id);
        if (index > -1) {
            const deletedTask = this.tasks.splice(index, 1);
            this.saveTasks();
            return deletedTask[0];
        }
        return null;
    }
    
    // 切换任务状态
    toggleTaskStatus(id) {
        const task = this.tasks.find(t => t.id === id);
        if (task) {
            const statusOrder = ['pending', 'in-progress', 'completed'];
            const currentIndex = statusOrder.indexOf(task.status);
            const nextIndex = (currentIndex + 1) % statusOrder.length;
            task.status = statusOrder[nextIndex];
            task.updatedAt = new Date().toISOString();
            this.saveTasks();
            return task;
        }
        return null;
    }
    
    // 根据状态筛选任务
    getTasksByStatus(status) {
        return this.tasks.filter(t => t.status === status);
    }
    
    // 根据优先级筛选任务
    getTasksByPriority(priority) {
        return this.tasks.filter(t => t.priority === priority);
    }
    
    // 保存任务到本地存储
    saveTasks() {
        try {
            localStorage.setItem('tasks', JSON.stringify(this.tasks));
        } catch (error) {
            console.error('保存任务失败:', error);
        }
    }
    
    // 从本地存储加载任务
    loadTasks() {
        try {
            const savedTasks = localStorage.getItem('tasks');
            if (savedTasks) {
                this.tasks = JSON.parse(savedTasks);
            }
        } catch (error) {
            console.error('加载任务失败:', error);
        }
    }
    
    // 获取今天的任务
    getTodayTasks() {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);
        
        return this.tasks.filter(task => {
            if (!task.dueDate) return false;
            const dueDate = new Date(task.dueDate);
            dueDate.setHours(0, 0, 0, 0);
            return dueDate >= today && dueDate < tomorrow;
        });
    }
    
    // 获取逾期任务
    getOverdueTasks() {
        const now = new Date();
        return this.tasks.filter(task => {
            if (!task.dueDate || task.status === 'completed') return false;
            return new Date(task.dueDate) < now;
        });
    }
}

// 导出单例实例
const taskManager = new TaskManager();
module.exports = taskManager;